package org.langcom.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.util.logging.Logger;

public class AloneSocketChecker {

	private static final String LOCALHOST = "localhost";
	private static final String SECOND_INSTANCES_ARE_PROGIBITED_APP_WILL_SHUTDOWN = "***Second instances are progibited - application will shutdowned.";

	public static ServerSocket checkAlone(int port) throws SecondInstanceException {
		ServerSocket serverSocket = null;
		try {
			serverSocket = new ServerSocket();
			InetSocketAddress address = new InetSocketAddress(LOCALHOST, port);
			try {
				serverSocket.bind(address);
				Logger.getLogger(AloneSocketChecker.class.getName()).info("***Application is alone at " + LOCALHOST + "  : " + serverSocket.getLocalPort());
				return serverSocket;
			} catch (Exception e) {
				Logger.getLogger(AloneSocketChecker.class.getName()).severe(SECOND_INSTANCES_ARE_PROGIBITED_APP_WILL_SHUTDOWN);
				throw new SecondInstanceException(SECOND_INSTANCES_ARE_PROGIBITED_APP_WILL_SHUTDOWN);
			}
		} catch (IOException e1) {
			throw new SecondInstanceException(SECOND_INSTANCES_ARE_PROGIBITED_APP_WILL_SHUTDOWN, e1);
		}
	}
}
